package com.core.family.gen.service.gen.Impl.mysql;

import com.core.family.gen.domain.po.TableBeanPo;
import com.core.family.gen.domain.po.TableColumnPo;
import com.core.family.gen.service.gen.Impl.AbsGenHandler;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: mybatis 相关代码生成 通过链接器获取数据库元信息实现
 * @author: honglei
 * @time: 2021/3/23 0023 14:48
 */

public class GenMysqlHandler extends AbsGenHandler {

    //查询表名
    private final static String QUEARY_TABLEAS =
            " select table_name as TABLE_NAME , engine, table_comment as REMARKS, create_time createTime " +
                    " from information_schema.tables where TABLE_SCHEMA = (select database()) ";

    //查询表字段及注释
    private final static String QUEARY_COLUMNS =
            " select column_name as COLUMN_NAME, data_type as TYPE_NAME, column_comment as REMARKS, column_key columnKey, extra " +
                    " from information_schema.columns  where table_name = '%s' and TABLE_SCHEMA = (select database()) ";


    @Override
    public List<TableBeanPo> tablesList() throws Exception {
        List<TableBeanPo> list = new ArrayList<>();

        if (list.size() == 0) {
            Connection connection = getConnection();
            ResultSet rs = connection.createStatement().executeQuery(QUEARY_TABLEAS);
            list = filledTableBean(rs);
            connection.clearWarnings();
        }
        return list;
    }


    @Override
    public List<TableColumnPo> getColumns(String table) throws Exception {

        List<TableColumnPo> list = new ArrayList<>();

        if (list.size() == 0) {
            String sql = String.format(QUEARY_COLUMNS, table);
            Connection connection = getConnection();
            ResultSet resultSet = connection.createStatement().executeQuery(sql);

//            PreparedStatement ps =connection.prepareStatement(QUEARY_COLUMNS);
//            ps.setString(0,table);
//            ResultSet resultSet=ps.executeQuery();
            list = filledTableColumn(resultSet);
            connection.close();
        }
        return list;
    }


}
